package com.dream.auth.security;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.dream.auth.entity.SysUser;
import com.dream.auth.mapper.SysUserMapper;
import com.dream.auth.model.LoginResponse;
import com.dream.auth.model.UserInfo;
import lombok.RequiredArgsConstructor;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;
import org.springframework.stereotype.Component;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@Component
@RequiredArgsConstructor
public class LoginSuccessHandler implements AuthenticationSuccessHandler {

    private final JwtUtils jwtUtils;
    private final ObjectMapper objectMapper;
    private final SysUserMapper sysUserMapper;

    @Override
    public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response,
            Authentication authentication) throws IOException, ServletException {
        
        UserDetails userDetails = (UserDetails) authentication.getPrincipal();
        String token = jwtUtils.generateToken(userDetails);

        // 获取用户信息
        SysUser user = sysUserMapper.selectOne(
            new com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper<SysUser>()
                .eq(SysUser::getUsername, userDetails.getUsername())
        );

        // 构建响应
        UserInfo userInfo = UserInfo.builder()
                .id(user.getId())
                .username(user.getUsername())
                .nickname(user.getNickName())
                .build();

        LoginResponse loginResponse = LoginResponse.builder()
                .token(token)
                .userInfo(userInfo)
                .build();

        // 判断是否是AJAX请求
        if (isAjaxRequest(request)) {
            response.setContentType("application/json;charset=UTF-8");
            response.getWriter().write(objectMapper.writeValueAsString(loginResponse));
        } else {
            // 普通表单提交，重定向到首页
            response.sendRedirect("/index");
        }
    }

    private boolean isAjaxRequest(HttpServletRequest request) {
        String xRequestedWith = request.getHeader("X-Requested-With");
        String contentType = request.getHeader("Content-Type");
        return "XMLHttpRequest".equals(xRequestedWith) 
            || (contentType != null && contentType.contains("application/json"));
    }
} 